package com.example.photography.Activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.example.photography.R;
import com.example.photography.adapter.Item_commentAdapter;
import com.example.photography.adapter.Label_ProtoAdapter;
import com.example.photography.adapter.PhotoAdapter;
import com.example.photography.bean.Product_bean;
import com.example.photography.bean.UrlBean;
import com.example.photography.common.BaseActivity;
import com.example.photography.common.Constant;
import com.example.photography.retrofit.ApiService;
import com.example.photography.retrofit.net.exception.ApiException;
import com.example.photography.retrofit.net.exception.ErrorConsumer;
import com.example.photography.retrofit.net.response.ResponseTransformer;
import com.example.photography.ui.CircleImageView;
import com.example.photography.util.Util;
import com.example.photography.view.CommentExpandableListView;
import com.example.photography.view.LoadingDialog;
import com.example.photography.view.Message_Dialog;
import com.example.photography.view.MyListView;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.bottomsheet.BottomSheetDialog;

import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import dagger.hilt.android.AndroidEntryPoint;
import io.reactivex.functions.Consumer;

import static com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions.withCrossFade;

/**
 * 作品详情
 */
@AndroidEntryPoint
public class Product_Content extends BaseActivity {


    @BindView(R.id.tl_iv_back)
    ImageView tlIvBack;
    @BindView(R.id.tl_tv_title)
    TextView tlTvTitle;
    @BindView(R.id.tl_iv_more)
    ImageView tlIvMore;
    @BindView(R.id.tl_iv_head)
    ImageView tlIvHead;
    @BindView(R.id.tl_tv_name)
    TextView tlTvName;
    @BindView(R.id.title_focus)
    TextView titleFocus;
    @BindView(R.id.tl_rl_item)
    RelativeLayout tlRlItem;
    @BindView(R.id.iv_head)
    CircleImageView ivHead;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_date)
    TextView tvDate;
    @BindView(R.id.tv_focus)
    TextView tvFocus;
    @BindView(R.id.rl_item)
    RelativeLayout rlItem;
    @BindView(R.id.tv_presentation)
    TextView tvPresentation;
    @BindView(R.id.lv_product)
    MyListView lvProduct;
    @BindView(R.id.tv_group)
    TextView tvGroup;
    @BindView(R.id.rv_label)
    RecyclerView rvLabel;
    @BindView(R.id.lv_comment)
    CommentExpandableListView lvComment;
    @BindView(R.id.ns_view)
    NestedScrollView nsView;
    @BindView(R.id.send_comment)
    TextView sendComment;
    @BindView(R.id.iv_collect)
    ImageView ivCollect;
    @BindView(R.id.tv_collects)
    TextView tvCollects;
    @BindView(R.id.iv_like)
    ImageView ivLike;
    @BindView(R.id.tv_likes)
    TextView tvLikes;
    @BindView(R.id.ll_bottom)
    LinearLayout llBottom;
    private Product_bean productBean;
    private Item_commentAdapter item_commentAdapter;
    private BottomSheetDialog dialog;
    private String product_id;
    //注入动态代理实例对象
    @Inject
    ApiService apiService;
    private Message_Dialog mMyDialog;

    @Override
    protected void initData() {
        productBean = new Product_bean();
        Intent intent = getIntent();
        Bundle bundle = intent.getBundleExtra("data");
        if (bundle != null && bundle.getString("product_id") != null) {
            product_id = bundle.getString("product_id");
            send_http();
        }else {
            Util.showToast(getApplicationContext(), "数据出错，请返回重试");
        }
        initListen();
    }

    @SuppressLint("CheckResult")
    private void send_http() {
        //开启等待动画
        LoadingDialog.getInstance(this).show();
        apiService.product_pro_id(product_id)
                .compose(ResponseTransformer.obtain())
                .subscribe(new Consumer<Product_bean>() {
                    @Override
                    public void accept(Product_bean product_bean) throws Exception {
                        productBean = product_bean;
                        mHandler.sendEmptyMessageDelayed(2,0);
                    }
                }, new ErrorConsumer() {
                    @Override
                    protected void error(ApiException e) {
                        LoadingDialog.getInstance(Product_Content.this).dismiss();
                        Message message = new Message();
                        message.what = 1;
                        message.obj = e.getErrorMsg();
                        mHandler.sendMessage(message);

                    }
                });
    }

    private void initListen() {
        //监听滑动
        nsView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                /**
                 * 上滑隐藏底部框
                 */
                if (scrollY > oldScrollY) {
                    llBottom.setVisibility(View.GONE);
                } else {
                    llBottom.setVisibility(View.VISIBLE);
                }

                /**
                 * 显示两个不一样的title
                 */
                if (scrollY >= 120) {
                    tlRlItem.setVisibility(View.VISIBLE);
                    tlIvMore.setVisibility(View.GONE);
                    tlTvTitle.setVisibility(View.GONE);
                } else {
                    tlRlItem.setVisibility(View.GONE);
                    tlIvMore.setVisibility(View.VISIBLE);
                    tlTvTitle.setVisibility(View.VISIBLE);
                }
            }
        });
        //返回iv监听
        tlIvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                removeCurrentActivity();
            }
        });
        //发表评论
        sendComment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showCommentDialog();
            }
        });
        //作者头像
        ivHead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                goToActivity(My_Activity.class, new Bundle());
            }
        });
        tlIvHead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                goToActivity(My_Activity.class, new Bundle());
            }
        });
        lvComment.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView expandableListView, View view, int groupPosition, long l) {
                showReplyDialog(groupPosition);
                return true;
            }
        });
        lvComment.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView expandableListView, View view, int groupPosition, int childPosition, long l) {
                showReplyDialog(groupPosition,childPosition);
                return false;
            }
        });

    }



    private void initView() {

        Glide.with(this)
                .load(productBean.getHead_url())
                .thumbnail(Glide.with(this).load(R.drawable.loading))
                .apply(RequestOptions.bitmapTransform(new RoundedCorners(40)))
                .into(ivHead);
        Glide.with(this)
                .load(productBean.getHead_url())
                .thumbnail(Glide.with(this).load(R.drawable.loading))
                .apply(RequestOptions.bitmapTransform(new RoundedCorners(40)))
                .into(tlIvHead);
        tvName.setText(productBean.getName());
        tlTvName.setText(productBean.getName());
        tvDate.setText(Util.getTimeFormatText(productBean.getTime()));
        tvPresentation.setText(productBean.getContent());
        List<UrlBean> urlBeans = JSONObject.parseArray(productBean.getProducts(), UrlBean.class);
        PhotoAdapter photoAdapter = new PhotoAdapter(urlBeans, this) {
            @Override
            public void onclick(String url) {
                setImage(url);
            }
        };
        // TODO: 2021/5/6 listview高度有问题
        lvProduct.setAdapter(photoAdapter);
        tvGroup.setText(productBean.getLabel().size() + "个圈子可看到");

        /**
         * 装载横向RecyclerView
         */
        //创建LinearLayoutManager
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        //RecyclerView设置为横向滑动
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        //设置创建LinearLayoutManager到RecyclerView中
        rvLabel.setLayoutManager(linearLayoutManager);
        Label_ProtoAdapter labelProtoAdapter = new Label_ProtoAdapter(productBean.getLabel(), this) {
            @Override
            protected void onclick(String lab_id) {
                Util.showToast(Product_Content.this, "点击了圈子，lab_id:" + lab_id);
            }
        };
        rvLabel.setAdapter(labelProtoAdapter);


        /**
         * 评论listview
         */
        lvComment.setGroupIndicator(null);
        item_commentAdapter = new Item_commentAdapter(productBean.getComments(), this) {
            @Override
            public void headListen() {
                goToActivity(My_Activity.class, new Bundle());
            }

            @Override
            public void reply_more(String pc_id) {

            }
        };
        lvComment.setAdapter(item_commentAdapter);
//        lvComment.expandGroup(0);

        //默认展开所有评论
        int count = lvComment.getCount()-1;
        for (int i=0; i<count; i++) {
            lvComment.expandGroup(i,true);
        };
    }

    /**
     * 弹出评论框
     */
    private void showCommentDialog() {
        // TODO: 2020/11/16 手机软键盘遮挡输入框
        dialog = new BottomSheetDialog(this);
        View commentView = LayoutInflater.from(this).inflate(R.layout.comment_dialog_layout, null);
        final EditText commentText = (EditText) commentView.findViewById(R.id.dialog_comment_et);
        final Button bt_comment = (Button) commentView.findViewById(R.id.dialog_comment_bt);
        dialog.setContentView(commentView);
        /**
         * 解决bsd显示不全的情况
         */
        View parent = (View) commentView.getParent();
        BottomSheetBehavior behavior = BottomSheetBehavior.from(parent);
        commentView.measure(0, 0);
        behavior.setPeekHeight(commentView.getMeasuredHeight());
        bt_comment.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("CheckResult")
            @Override
            public void onClick(View view) {
                String commentContent = commentText.getText().toString().trim();
                if (!TextUtils.isEmpty(commentContent)) {
                    //commentOnWork(commentContent);

                    apiService.add_pro_comment(productBean.getProduct_id(),Constant.UID,commentContent)
                            .compose(ResponseTransformer.obtain())
                            .subscribe(new Consumer<Product_bean.CommentsBean>() {
                                @Override
                                public void accept(Product_bean.CommentsBean commentsBean) throws Exception {
                                    item_commentAdapter.addTheCommentData(commentsBean);
                                    dialog.dismiss();
                                }
                            }, new ErrorConsumer() {
                                @Override
                                protected void error(ApiException e) {
                                    Util.show(Product_Content.this, "评论失败:"+e.getErrorMsg());
                                }
                            });
//                    //获取当前时间
//                    Date date = new Date(System.currentTimeMillis());
//                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                    Product_bean.CommentsBean comment = new Product_bean.CommentsBean();
//                    comment.setId_unique("111");
//                    comment.setHead_url("http://114.55.249.135:8888/touxiang/a.png");
//                    comment.setName("浩南仔");
//                    comment.setContent(commentContent);
//                    comment.setTime(simpleDateFormat.format(date));
//                    item_commentAdapter.addTheCommentData(comment);

                    Util.show(Product_Content.this, "评论成功");
                } else {
                    Util.show(Product_Content.this, "评论内容不能为空");
                }
            }
        });

        commentText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (!TextUtils.isEmpty(charSequence) && charSequence.length() > 2) {
                    bt_comment.setBackgroundColor(Color.parseColor("#FFB568"));
                } else {
                    bt_comment.setBackgroundColor(Color.parseColor("#D8D8D8"));
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        dialog.show();

    }

    /**
     * 弹出回复框
     */
    private void showReplyDialog(final int groupPosition) {
        dialog = new BottomSheetDialog(this);
        View commentView = LayoutInflater.from(this).inflate(R.layout.comment_dialog_layout, null);
        final EditText commentText = (EditText) commentView.findViewById(R.id.dialog_comment_et);
        final Button bt_comment = (Button) commentView.findViewById(R.id.dialog_comment_bt);
        commentText.setHint("回复 " + productBean.getComments().get(groupPosition).getObserver_name() + " 的评论:");
        dialog.setContentView(commentView);
        bt_comment.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("CheckResult")
            @Override
            public void onClick(View view) {
                String replyContent = commentText.getText().toString().trim();
                if (!TextUtils.isEmpty(replyContent)) {
                    apiService.add_pro_reply(productBean.getComments().get(groupPosition).getPc_id(),Constant.UID,productBean.getComments().get(groupPosition).getPc_id(),replyContent)
                            .compose(ResponseTransformer.obtain())
                            .subscribe(new Consumer<Product_bean.CommentsBean.ReplysBean>() {
                                @Override
                                public void accept(Product_bean.CommentsBean.ReplysBean replysBean) throws Exception {
                                    item_commentAdapter.addTheReplyData(replysBean, groupPosition);
                                    lvComment.expandGroup(groupPosition);
                                    Util.showToast(Product_Content.this, "回复成功");
                                    dialog.dismiss();
                                }
                            }, new ErrorConsumer() {
                                @Override
                                protected void error(ApiException e) {
                                    Util.showToast(Product_Content.this, "回复失败："+e.getErrorMsg());
                                }
                            });
                } else {
                    Util.showToast(Product_Content.this, "回复内容不能为空");
                }
            }
        });
        commentText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (!TextUtils.isEmpty(charSequence) && charSequence.length() > 2) {
                    bt_comment.setBackgroundColor(Color.parseColor("#FFB568"));
                } else {
                    bt_comment.setBackgroundColor(Color.parseColor("#D8D8D8"));
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        dialog.show();
    }

    private void showReplyDialog(int groupPosition, int childPosition) {
        dialog = new BottomSheetDialog(this);
        View commentView = LayoutInflater.from(this).inflate(R.layout.comment_dialog_layout, null);
        final EditText commentText = (EditText) commentView.findViewById(R.id.dialog_comment_et);
        final Button bt_comment = (Button) commentView.findViewById(R.id.dialog_comment_bt);
        commentText.setHint("回复 " + productBean.getComments().get(groupPosition).getObserver_name() + " 的回复:");
        dialog.setContentView(commentView);
        bt_comment.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("CheckResult")
            @Override
            public void onClick(View view) {
                String replyContent = commentText.getText().toString().trim();
                if (!TextUtils.isEmpty(replyContent)) {
                    apiService.add_pro_reply(productBean.getComments().get(groupPosition).getPc_id(),Constant.UID,productBean.getComments().get(groupPosition).getReplys().get(childPosition).getReply_id(),replyContent)
                            .compose(ResponseTransformer.obtain())
                            .subscribe(new Consumer<Product_bean.CommentsBean.ReplysBean>() {
                                @Override
                                public void accept(Product_bean.CommentsBean.ReplysBean replysBean) throws Exception {
                                    item_commentAdapter.addTheReplyData(replysBean, groupPosition);
                                    lvComment.expandGroup(groupPosition);
                                    Util.showToast(Product_Content.this, "回复成功");
                                    dialog.dismiss();
                                }
                            }, new ErrorConsumer() {
                                @Override
                                protected void error(ApiException e) {
                                    Util.showToast(Product_Content.this, "回复失败："+e.getErrorMsg());
                                }
                            });
                } else {
                    Util.showToast(Product_Content.this, "回复内容不能为空");
                }
            }
        });
        commentText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (!TextUtils.isEmpty(charSequence) && charSequence.length() > 2) {
                    bt_comment.setBackgroundColor(Color.parseColor("#FFB568"));
                } else {
                    bt_comment.setBackgroundColor(Color.parseColor("#D8D8D8"));
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        dialog.show();
    }
    private void setImage(String url) {//展开图片//todo 单击图片消失,手势放大缩小功能待实现
        View view = getLayoutInflater().inflate(R.layout.full_image, null);
        ImageView imageView = view.findViewById(R.id.image);//获取diolog里面的返回键和确定键
        //加载网络图片
        Glide.with(this)
                .load(url)
                .transition(withCrossFade()) //Glide提供淡如淡出
                .into(imageView);
        mMyDialog = new Message_Dialog(this, 0, 0, view, R.style.DialogTheme);
//        让自定义dialog的宽度充满整个屏幕
        WindowManager windowManager = this.getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        WindowManager.LayoutParams lp = mMyDialog.getWindow().getAttributes();
        lp.width = (int) (display.getWidth()); //设置宽度
        mMyDialog.getWindow().setAttributes(lp);
        mMyDialog.show();
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mMyDialog.dismiss();
            }
        });
    }
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1://查询失败
                    Util.showToast(Product_Content.this, "获取文章失败："+msg.obj);
                    LoadingDialog.getInstance(Product_Content.this).dismiss();
                    break;
                case 2://查询成功
                    LoadingDialog.getInstance(Product_Content.this).dismiss();
                    initView();//装载数据进组件
                    break;


            }
        }
    };
    @Override
    protected int getLayoutId() {
        return R.layout.product_content;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //防止窗体泄漏
        if (mMyDialog != null) {
            mMyDialog.dismiss();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
